package com.tx.axure.tkaxureweb.service;

import com.tx.axure.tkaxureweb.domain.entity.SProd;
import com.tx.axure.tkaxureweb.mapper.SProdMapper;
import com.tx.axure.tkaxureweb.vo.ResultVoMap;
import com.tx.utils.CalculateUtils;
import com.tx.utils.DateUtils;
import com.tx.utils.FileUtils;
import com.tx.utils.UnzipUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FilesServiceImpl implements IFilesService {

    @Value("${file.path}")
    private String uploadPath;

    private final SProdMapper sProdMapper;

    private String getUploadPath() {//智能识别补全路径
        Properties props = System.getProperties();
        String property = props.getProperty("os.name");
        String userHomePath = props.getProperty("user.home");
        String filePath = "";//文件存放地址
        if (property.contains("Windows")) {
            String[] arr = userHomePath.split(":");
            String pan = arr[0] + ":";//windows会取第一个盘盘符
            filePath = pan + uploadPath;
        } else {
            filePath = uploadPath;
        }
        return filePath;
    }

    @Override
    public ResultVoMap uploadFile(MultipartFile file,Integer prodId) {
        //根据prod获取信息
        SProd sProd=sProdMapper.selectByPrimaryKey(prodId);

        String originalFilename = file.getOriginalFilename();//原始名称
        if ((null == originalFilename && "".equals(originalFilename)) || !originalFilename.endsWith(".zip")) {
            return new ResultVoMap(new Exception("请上传以.zip格式压缩包"));
        }
        String newName = UUID.randomUUID().toString().replace("-", "");//uuid作为文件夹新名称,不重复
        //String zipName = newName + ".zip";//uuid作为压缩文件新名称,不重复
        String zipName = sProd.getHostName() + ".zip";//uuid作为压缩文件新名称,不重复
        //创建文件夹，今天的日期
        String date = DateUtils.getDate();
        //文件存放位置，加一层日期
        String path = getUploadPath();
        //返回结果
        Map<String, Object> pathMap = new HashMap<>();
        InputStream inputStream = null;//文件流
        try {
            inputStream = file.getInputStream();
            //检测创建文件夹
            Path directory = Paths.get(path);
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }else{
                //文件已经上传过则存在目录，需要删除
//                File dic=new File(path);
//                dic.delete();
            }
            String prodUnzipFolderPath=path+File.separator +sProd.getHostName();
            File prodUnzipFolderPathFile=new File(prodUnzipFolderPath);
            if(prodUnzipFolderPathFile.exists()){
                //如果解压后的文件存在，则删除解压包
                FileUtils.delFolder(prodUnzipFolderPath);
            }
            File prodZipFile=new File( path + File.separator + zipName);
            if(prodZipFile.exists()){
                //如果同样名称的压缩包存在，则删除
                prodZipFile.delete();
            }
            Long size = Files.copy(inputStream, directory.resolve(zipName));//上传文件，返回值是文件大小

            String fileSize = "";
            float num =(float)size/1024;
            DecimalFormat df = new DecimalFormat("0.00");

            if(num<1024){
                fileSize= df.format(num)+"KB";
            }else{
                fileSize=df.format(num/1024)+"M";
            }

            pathMap.put("zip_size",fileSize);

            SProd sProd1=SProd.builder()
                    .id(sProd.getId())
                    .fileSize(fileSize)
                    .updateTime(new Date())
                    .build();
            sProdMapper.updateByPrimaryKeySelective(sProd1);
        } catch (Exception e) {
            pathMap.put("zip_size", 0);
            return new ResultVoMap(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        String zipPath = path + File.separator + zipName;
        if(!UnzipUtils.zipUncompress(zipPath,null)){
            UnzipUtils.zipUncompress(zipPath,"GBK");
        }
        pathMap.put("main_path", zipPath);
        pathMap.put("folder_path", path + File.separator + newName);
        pathMap.put("zip_size_cent", "kb");
        return new ResultVoMap(pathMap);
    }

}


